﻿using ALMDDD.Domain.Commands.SysUser;
using ALMDDD.Domain.Core.Bus;
using ALMDDD.Domain.Interfaces;
using ALMDDD.Domain.Interfaces.Repository;
using ALMDDD.Domain.Model;
using MediatR;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ALMDDD.Domain.CommandHandlers
{
    /// <summary>
    /// 用户命令处理程序
    /// </summary>
    public class SysUserCommandHandler : CommandHandler,
         IRequestHandler<AddUserCommand, Unit>
    {
        private readonly ISysUserRepository _sysUserRepository;//用户仓储
        private readonly IMeDiatorHandler _bus;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="unitOfWork">工作单元</param>
        /// <param name="bus">中介者总线服务</param>
        public SysUserCommandHandler(IunitOfWork unitOfWork,
            IMeDiatorHandler bus,
            ISysUserRepository sysUserRepository) : base(unitOfWork, bus)
        {
            _sysUserRepository = sysUserRepository;
            _bus = bus;
        }

        public Task<Unit> Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return Task.FromResult(new Unit());
            }
            // 实例化领域模型，这里才真正的用到了领域模型
            // 注意这里是通过构造函数方法实现
            var sysUserModel = new Sys_User(Guid.NewGuid(), request.UserId, request.UserName, request.Gender, request.PassWord, request.Email, request.Phone, request.TrxTime,null);
            _sysUserRepository.Add(sysUserModel);
            if (Commit())
            {
                //_bus.RaiseEvent(new )
            }


            return Task.FromResult(new Unit());
        }
    }
}
